package top.kaoshanji.p2ch16a;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

import static top.kaoshanji.p2ch16a.Util.delay;

/**
 * author kaoshanji
 * ^_^
 * create time 2025/2/14 19:05
 */
public class AsyncShop {

    private final String name;
    private final Random random;

    public AsyncShop(String name) {
        this.name = name;
        random = new Random(name.charAt(0) * name.charAt(1) * name.charAt(2));
    }

    // 代码清单-p2ch16a-351页a：使用工厂方法supplyAsync创建CompletableFuture对象
    public Future<Double> getPrice(String product) {
        return CompletableFuture.supplyAsync(() -> calculatePrice(product));
    }

    private double calculatePrice(String product) {
        delay();
        if (true) {
            throw new RuntimeException("product not available");
        }
        return Util.format(random.nextDouble() * product.charAt(0) + product.charAt(1));
    }

}
